package com.example.demo1.service.impl.service.impl;

import com.example.demo1.common.ResponseCode;
import com.example.demo1.common.ServerResponse;
import com.example.demo1.entity.BaRole;
import com.example.demo1.entity.BaRoleFunction;
import com.example.demo1.mapper.BaRoleFunctionMapper;
import com.example.demo1.mapper.BaRoleMapper;
import com.example.demo1.service.impl.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Transactional
@Service
public class RoleServiceImpl implements RoleService {

    private Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private BaRoleMapper roleMapper;

    @Autowired
    private BaRoleFunctionMapper roleFunctionMapper;

    public ServerResponse queryRoles(String roleName, int pageNum, int pageSize){

        logger.info("时间：" + new Date() + "=================RoleServiceImpl.queryRoles方法调用开始");
        PageHelper.startPage(pageNum, pageSize);
        List<BaRole> roles = roleMapper.selectRolesByRoleName(roleName);
        Map<String, Object> resultItem;
        List<Map<String, Object>> result = new ArrayList<>();
        if(!CollectionUtils.isEmpty(roles)){
            for(BaRole roleItem : roles){
                List<Integer> roleFunctionIds = roleFunctionMapper.selectFunctionIdsByRoleId(roleItem.getRoleId());
                if(CollectionUtils.isEmpty(roleFunctionIds)){
                    roleFunctionIds = new ArrayList<>();
                }
                resultItem = new LinkedHashMap<>();
                resultItem.put("roleId", roleItem.getRoleId());
                resultItem.put("roleName", roleItem.getRoleName());
                resultItem.put("remark", roleItem.getRemark());
                resultItem.put("roleFunctionIds", roleFunctionIds);
                result.add(resultItem);
            }
        }
        PageInfo pageInfo = new PageInfo(roles);
        pageInfo.setList(result);
        logger.info("时间：" + new Date() + "=================RoleServiceImpl.queryRoles方法执行成功");
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse addRoleInfo(BaRole role,Integer userId, String functionIds) {

        logger.info("时间：" + new Date() + "=================RoleServiceImpl.addRoleInfo方法调用开始");
        if(role == null || functionIds == null){
            logger.info("时间：" + new Date() + "=================RoleServiceImpl.addRoleInfo方法参数校验不通过");
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        if (roleMapper.selectRoleByRoleName(role.getRoleName()) !=null){
            logger.error("时间：" + new Date() + "===================RoleServiceImpl.addRoleInfo方法角色名称已存在");
            return ServerResponse.createByErrorMessage("角色名称已存在,请重新填写");
        }
        role.setUpdateTime(new Date());
        int insertNum = roleMapper.insert(role);
        int insertFuncNum;
        BaRoleFunction roleFunction;
        if(insertNum > 0){
            if(!StringUtils.isEmpty(functionIds)){
                List<String> functionIdsList =Arrays.asList(functionIds.split(",",-1));
                if(!CollectionUtils.isEmpty(functionIdsList)){
                    for(String functionId : functionIdsList){
                        roleFunction = new BaRoleFunction();
                        roleFunction.setRoleId(role.getRoleId());
                        roleFunction.setFunctionId(Integer.valueOf(functionId));
                        roleFunction.setUpdateUser(userId.toString());
                        roleFunction.setUpdateTime(new Date());
                        insertFuncNum = roleFunctionMapper.insert(roleFunction);
                        if(insertFuncNum <= 0){
                            logger.error("时间：" + new Date() + "===================RoleServiceImpl.addRoleInfo方法添加角色权限关联信息出错");
                            throw new RuntimeException("时间：" + new Date() + "===================RoleServiceImpl.addRoleInfo方法添加角色权限关联信息出错");
                        }
                    }
                }
            }
            logger.info("时间：" + new Date() + "===================RoleServiceImpl.addRoleInfo方法执行成功");
            return ServerResponse.createBySuccess();
        }
        logger.error("时间：" + new Date() + "===================RoleServiceImpl.addRoleInfo方法添加角色信息失败");
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
    }

    @Override
    public ServerResponse editRoleInfo(BaRole role,Integer userId, String functionIds) {
        logger.info("时间：" + new Date() + "=================RoleServiceImpl.editRoleInfo方法调用开始");
        if(role == null || functionIds == null){
            logger.info("时间：" + new Date() + "=================RoleServiceImpl.editRoleInfo方法参数校验不通过");
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        if (roleMapper.selectRoleByRoleNameNotSelf(role.getRoleName(),role.getRoleId()) != null){
            logger.error("时间：" + new Date() + "===================RoleServiceImpl.editRoleInfo方法角色名称已存在");
            return ServerResponse.createByErrorMessage("角色名称已存在,请重新填写");
        }
        role.setUpdateTime(new Date());
        Integer editNum = roleMapper.updateByPrimaryKey(role);
        Integer insertFuncNum;
        BaRoleFunction roleFunction;
        if(editNum > 0){
            int deleteNum = roleFunctionMapper.deleteByRoleId(role.getRoleId());
            if(deleteNum < 0){
                throw new RuntimeException("时间：" + new Date() + "===================RoleServiceImpl.editRoleInfo方法更新角色权限信息失败");
            }
            if(!StringUtils.isEmpty(functionIds)){
                List<String> functionIdsList = Arrays.asList(functionIds.split(",",-1));
                if(!CollectionUtils.isEmpty(functionIdsList)){
                    for(String functionId : functionIdsList){
                        roleFunction = new BaRoleFunction();
                        roleFunction.setRoleId(role.getRoleId());
                        roleFunction.setFunctionId(Integer.valueOf(functionId));
                        roleFunction.setUpdateUser(userId.toString());
                        roleFunction.setUpdateTime(new Date());
                        insertFuncNum = roleFunctionMapper.insert(roleFunction);
                        if(insertFuncNum <= 0){
                            logger.error("时间：" + new Date() + "===================RoleServiceImpl.editRoleInfo方法添加角色权限关联信息出错");
                            throw new RuntimeException("时间：" + new Date() + "===================RoleServiceImpl.editRoleInfo方法添加角色权限关联信息出错");
                        }
                    }
                }
            }
            logger.info("时间：" + new Date() + "===================RoleServiceImpl.editRoleInfo方法执行成功");
            return ServerResponse.createBySuccess();
        }
        logger.error("时间：" + new Date() + "====================RoleServiceImpl.editRoleInfo方法执行失败");
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
    }

    @Override
    public ServerResponse deleteRoleInfo(String roleIds) {
        logger.info("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法调用开始");
        if(StringUtils.isEmpty(roleIds)){
            logger.error("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法参数校验不通过");
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<String> roleIdList = Arrays.asList(roleIds.split(",",-1));
        if(CollectionUtils.isEmpty(roleIdList)){
            logger.error("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法参数截取失败");
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
        }
        Integer deleteNum;
        for(String roleId : roleIdList){
            List<Integer> functionIds = roleFunctionMapper.selectFunctionIdsByRoleId(Integer.valueOf(roleId));
            if(!CollectionUtils.isEmpty(functionIds) && !(functionIds.size() == 0)){
                logger.error("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法将删除的角色还关联功能信息");
                return ServerResponse.createByErrorMessage("该角色还关联有功能信息,请取消关联后再进行删除");
            }
            deleteNum = roleMapper.deleteByPrimaryKey(Integer.valueOf(roleId));
            if(deleteNum <= 0){
                logger.error("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法删除角色信息失败");
                throw new RuntimeException("时间：" + new Date() + "=================RoleServiceImpl.deleteRoleInfo方法删除角色信息失败");
            }
        }
        logger.info("时间：" + new Date() + "===================RoleServiceImpl.deleteRoleInfo方法执行成功");
        return ServerResponse.createBySuccess();
    }

}
